<?php

namespace Home\Controller;

use Think\Controller;
use Think\Upload;
use Common\Top;
use Common\Utils;
use Common\Sms;

class PersonalController extends CommonController
{


    public function index()
    {
        $isLogin = session('isLogin');
        if ($isLogin == 'yes') {
            $agencyInfo = $this->userInfo;

            $baseUrl = C('MOFILE_BASE_URL');
            $headPic = $baseUrl . $agencyInfo['head_pic'];
            $headPic = Utils::GetImageUrl($headPic, 160, 160, 0);

            $bgPic = $baseUrl . $agencyInfo['bg_pic'];
            $bgPic = Utils::GetImageUrl($bgPic, 720, 720, 0);

            $weixinQrcode = $baseUrl . $agencyInfo['weixin_qrcode'];
            $weixinQrcode = Utils::GetImageUrl($weixinQrcode, 160, 160, 0);

            $this->assign('headPic', $headPic);
            $this->assign('bgPic', $bgPic);
            $this->assign('weixinQrcode', $weixinQrcode);
            $this->assign('userList', $agencyInfo);
            $this->assign('agency', $agencyInfo);
            $this->display();
        } else {
            $domain = $_SERVER['SERVER_NAME'];
            $url = "http://" . $domain . "/index.php";
            header("Location:" . $url);
        }
    }


    public function postEdit()
    {
        $isLogin = session('isLogin');
        if ($isLogin == 'yes') {
            $userList = $this->userInfo;

            if (IS_POST) {
                $where['entity_id'] = $userList['id'];
                $where['entity_type'] = Top::EntityTypeAgency;
                $where['operator_id'] = $userList['operator_id'];
                $data['login_pwd'] = Utils::getHashPwd(I('confirm_password'));
                $data['update_time'] = date('Y-m-d H:i:s', time());
                M('user')->where($where)->save($data);
                $this->redirect('Personal/index');
            }
        } else {
            $domain = $_SERVER['SERVER_NAME'];
            $url = "http://" . $domain . "/index.php";
            header("Location:" . $url);
        }
    }
    //处理意见反馈(C客户，顾问)
    public function agencyFeedback()
    {
        $isLogin = session('isLogin');
        if ($isLogin == 'yes') {
            $userList = $this->userInfo;
            if (IS_POST) {
                $data['agency_name'] = $userList['name'];
                $data['agency_id'] = $userList['id'];
                $data['cover_commnet_id'] = I('supplier_id');
                $data['cover_commnet_name'] = getSupplierName(I('supplier_id'));
                $data['star'] = I('star');
                $data['comm_content'] = I('comm_content');
                $data['operator_id'] = $userList['operator_id'];
                $data['create_time'] = date('Y-m-d H:i:s', time());
                $data['comment_type'] = 1;
                $res = M('feedback')->add($data);
                if($res){
                    $datas['status']=1;
                    $datas['msg']="谢谢，意见反馈成功";
                    $this->ajaxReturn($datas);
                }else{
                    $datas['status'] = -1;
                    $datas['msg'] = "失败，请重新反馈";
                    $this->ajaxReturn($datas);
                }
            }
        } else {
            $userList = $this->userInfo;
            if (IS_POST) {
                $data['agency_name'] = 'C客户';
                $data['cover_commnet_id'] = $userList['id'];
                $data['cover_commnet_name'] = $userList['name'];
                $data['star'] = I('star');
                $data['comm_content'] = I('comm_content');
                $data['operator_id'] = $userList['operator_id'];
                $data['create_time'] = date('Y-m-d H:i:s', time());
                $data['comment_type'] = 0;
                $res = M('feedback')->add($data);
                if($res){
                    $datas['status']=1;
                    $datas['msg']="谢谢，意见反馈成功";
                    $this->ajaxReturn($datas);
                }else{
                    $datas['status'] = -1;
                    $datas['msg'] = "失败，请重新反馈";
                    $this->ajaxReturn($datas);
                }
            }
        }
    }
    //查询当前顾问被C客户意见反馈列表
    public function userFeedback(){
        $isLogin = session('isLogin');
        if($isLogin == 'yes'){
              $page = I('page');

            if ($page == '') {
                $page = 1;
            }

            $html = $this->userFeedbackListGetPageHtml($page);

            if (IS_POST && IS_AJAX) {
                $this->ajaxReturn($html);
            } else {
                $this->assign('html', $html);
            }

            $this->display();
        }else{
            $domain = $_SERVER['SERVER_NAME'];
            $url = "http://".$domain . "/index.php";
            header("Location:" . $url);
        }
    }

    public function edit()
    {
        $isLogin = session('isLogin');
        if ($isLogin == 'yes') {
            $M = M();
            $agencyInfo = $this->userInfo;
            $where['entity_id'] = $agencyInfo['id'];
            $where['entity_type'] = Top::EntityTypeAgency;
            $where['operator_id'] = $agencyInfo['operator_id'];
            $userList = $M->table('top_user')->where($where)->find();

            $baseUrl = C('MOFILE_BASE_URL');
            $headPic = $baseUrl . $agencyInfo['head_pic'];
            $headPic = Utils::GetImageUrl($headPic, 160, 160, 0);
            $bgPic = $baseUrl . $agencyInfo['bg_pic'];
            $bgPic = Utils::GetImageUrl($bgPic, 720, 720, 0);

            $weixinQrcode = $baseUrl . $agencyInfo['weixin_qrcode'];
            $weixinQrcode = Utils::GetImageUrl($weixinQrcode, 160, 160, 0);

            $this->assign('headPic', $headPic);
            $this->assign('bgPic', $bgPic);
            $this->assign('weixinQrcode', $weixinQrcode);
            $this->assign('list', $agencyInfo);
            $this->assign('userList', $userList);

            $this->display();
        } else {
            $domain = $_SERVER['SERVER_NAME'];
            $url = "http://" . $domain . "/index.php";
            header("Location:" . $url);
        }
    }


//用户中心-页面设置
    public function pageSetting()
    {
        $isLogin = session('isLogin');
        if ($isLogin == 'yes') {
            $agencyInfo = $this->userInfo;

            $baseUrl = C('MOFILE_BASE_URL');
            $headPic = $baseUrl . $agencyInfo['head_pic'];
            $headPic = Utils::GetImageUrl($headPic, 160, 160, 0);

            $bgPic = $baseUrl . $agencyInfo['bg_pic'];
            $bgPic = Utils::GetImageUrl($bgPic, 720, 720, 0);

            $weixinQrcode = $baseUrl . $agencyInfo['weixin_qrcode'];
            $weixinQrcode = Utils::GetImageUrl($weixinQrcode, 160, 160, 0);

            $this->assign('userList', $agencyInfo);
            $this->assign('headPic', $headPic);
            $this->assign('bgPic', $bgPic);
            $this->assign('weixinQrcode', $weixinQrcode);
            $this->assign('list', $agencyInfo);
            $this->display();
        } else {
            $domain = $_SERVER['SERVER_NAME'];
            $url = "http://" . $domain . "/index.php";
            header("Location:" . $url);
        }
    }
//用户中心-模块排序
    public function column_sort() {
        $isLogin = session('isLogin');
        if ($isLogin == 'yes') {
            $agencyInfo = $this->userInfo;
            if (IS_POST) {
                $list = I('name');
                $list_info = implode(',',$list);
                $agency = M('agency');
                $data = array('column_sort'=>$list_info);
                $agencyInfo_id = $agencyInfo['id'];
                $res = $agency->where('id='.$agencyInfo_id)->setField($data);
                $this->redirect('Personal/index');
            } else {
                if ($agencyInfo['column_sort'] == 0) {
                    $info = '1,2,3,4,5,6,7,8';
                } else {
                    $info = $agencyInfo['column_sort'];
                }
                $info_arr = explode(",", $info);

                //获取首页栏目二维数组
                $Column_list = getColumnSort();
                foreach ($info_arr as $k => $vo) {
                    $Column_list[$k]['sort'] = $vo;
                }
                $this->assign('userList', $agencyInfo);
                $this->assign('Column_list', $Column_list);
                $this->display();
            }
        } else {
            $domain = $_SERVER['SERVER_NAME'];
            $url = "http://" . $domain . "/index.php";
            header("Location:" . $url);
        }
    }

    public function postPageSetting()
    {
        $isLogin = session('isLogin');
        if ($isLogin == 'yes') {
            $userList = $this->userInfo;

            if (IS_POST) {
                $id['id'] = $userList['id'];
                $where['id'] = $userList['id'];

                $fileHead = $_FILES['head']['name'];
                $fileBg = $_FILES['bg']['name'];
                $fileQrCode = $_FILES['qrCode']['name'];

                if ($fileHead == '' && $fileBg == '' && $fileQrCode == '') {

                } else {
                    $config = array(
                        'maxSize' => 10485760,
                        'rootPath' => C('AGENCY_UPLOAD_PATH'),
                        'savePath' => '/',
                        'saveRule' => time,
                        'exts' => array('jpg', 'gif', 'png', 'jpeg'),
                        'subName' => array('date', 'Ymd'),
                    );

                    $upload = new \Think\Upload($config);
                    $uploadInfo = $upload->upload();

                    if (!$uploadInfo) {
                        $this->error($upload->getError());
                    }

                    //上传成功 获取上传文件信息
                    $bgPath = $uploadInfo['bg']['savepath'] . $uploadInfo['bg']['savename'];
                    $headPath = $uploadInfo['head']['savepath'] . $uploadInfo['head']['savename'];
                    $qrCodePath = $uploadInfo['qrCode']['savepath'] . $uploadInfo['qrCode']['savename'];
                }

                if ($uploadInfo['head']['name'] != '') {
                    $picInfo['head_pic'] = $headPath;
                }
                if ($uploadInfo['bg']['name'] != '') {
                    $picInfo['bg_pic'] = $bgPath;
                }
                if ($uploadInfo['qrCode']['name'] != '') {
                    $picInfo['weixin_qrcode'] = $qrCodePath;
                }
                $picInfo['update_time'] = date('Y-m-d H:i:s', time());

                $nick_name = I('nick_name');
                if (!empty($nick_name)) {
                    $picInfo['nick_name'] = I('nick_name');
                } else {
                    $picInfo['nick_name'] = $userList['nick_name'];
                }

                $share_home_title = I('share_home_title');
                if (!empty($share_home_title)) {
                    $picInfo['share_home_title'] = I('share_home_title');
                } else {
                    $picInfo['share_home_title'] = $userList['share_home_title'];
                }

                M('agency')->where($id)->save($picInfo);
                $this->redirect('Personal/index');
            }
        } else {
            $domain = $_SERVER['SERVER_NAME'];
            $url = "http://" . $domain . "/index.php";
            header("Location:" . $url);
        }
    }


    public function myorder()
    {
        $isLogin = session('isLogin');
        if ($isLogin == 'yes') {
            $page = I('page');

            if ($page == '') {
                $page = 1;
            }

            $html = $this->myorderListGetPageHtml($page);

            if (IS_POST && IS_AJAX) {
                $this->ajaxReturn($html);
            } else {
                $this->assign('html', $html);
            }

            $this->display();
        } else {
            $domain = $_SERVER['SERVER_NAME'];
            $url = "http://" . $domain . "/index.php";
            header("Location:" . $url);
        }
    }


    public function otherOrder()
    {
        $isLogin = session('isLogin');

        if ($isLogin == 'yes') {
            $page = I('page');

            if ($page == '') {
                $page = 1;
            }

            $html = $this->otherOrderListGetPageHtml($page);

            if (IS_POST && IS_AJAX) {
                $this->ajaxReturn($html);
            } else {
                $this->assign('html', $html);
            }

            $this->display();
        } else {
            $domain = $_SERVER['SERVER_NAME'];
            $url = "http://" . $domain . "/index.php";
            header("Location:" . $url);
        }
    }


    public function myrecommend()
    {
        $isLogin = session('isLogin');
        if ($isLogin == 'yes') {
            $page = I('page');

            if ($page == '') {
                $page = 1;
            }

            $html = $this->myRecommendListGetPageHtml($page);

            if (IS_POST && IS_AJAX) {
                $this->ajaxReturn($html);
            } else {
                $this->assign('html', $html);
            }

            $this->display();
        } else {
            $domain = $_SERVER['SERVER_NAME'];
            $url = "http://" . $domain . "/index.php";
            header("Location:" . $url);
        }
    }


    public function delete()
    {
        $isLogin = session('isLogin');
        if ($isLogin == 'yes') {
            $id = I('id', 0, 'int');
            M('agency_tour')->where("id='{$id}'")->delete();
            $this->redirect('Personal/myrecommend');
        } else {
            $domain = $_SERVER['SERVER_NAME'];
            $url = "http://" . $domain . "/index.php";
            header("Location:" . $url);
        }
    }


    public function showAllPayed()
    {
        $isLogin = session('isLogin');

        if ($isLogin == 'yes') {
            $_SESSION['allPayedCode'] = 400;
            $userInfo = $this->userInfo;
            $M = M();

            $id = intval(I('get.id'));
            $orderTourList = $M->table('top_tour as t,top_order_tour as o')
                ->where("o.id ='{$id}'&& o.tour_id = t.id")
                ->field(array(
                    'o.id' => 'id',
                    't.name' => 'name',
                    't.cover_pic' => 'cover_pic',
                    'o.client_adult_count' => 'client_adult_count',
                    'o.client_child_count' => 'client_child_count',
                    'o.start_time' => 'start_time',
                    'o.price_total' => 'price_total',
                    'o.price_adjust' => 'price_adjust',
                    'o.state' => 'state',
                    'o.memo' => 'memo',
                ))
                ->find();


            $pic = substr($orderTourList['cover_pic'], 0, 7);
            $picUrl = str_replace($pic, C('FILE1_BASE_URL'), $orderTourList['cover_pic']);
            $pic = Utils::GetImageUrl($picUrl, 240, 160, 1);

            $totalMoney = Utils::getYuan($orderTourList['price_total'] + $orderTourList['price_adjust']);
            $orderTourList['start_time'] = substr($orderTourList['start_time'], 0, 10);

            $this->assign('userInfo', $userInfo);
            $this->assign('pic', $pic);
            $this->assign('totalMoney', $totalMoney);
            $this->assign('orderTourList', $orderTourList);

            $this->display();
        } else {
            $domain = $_SERVER['SERVER_NAME'];
            $url = "http://" . $domain . "/index.php";
            header("Location:" . $url);
        }
    }


    public function showPrePayed()
    {
        $isLogin = session('isLogin');
        if ($isLogin == 'yes') {
            $_SESSION['prePayedCode'] = 400;
            $userInfo = $this->userInfo;
            $M = M();

            $id = intval(I('get.id'));
            $orderTourList = $M->table('top_order_tour as o')
                ->where("o.id ='{$id}'")
                ->field(array(
                    'o.id' => 'id',
                    'o.tour_id' => 'tour_id',
                    'o.client_adult_count' => 'client_adult_count',
                    'o.client_child_count' => 'client_child_count',
                    'o.start_time' => 'start_time',
                    'o.price_total' => 'price_total',
                    'o.price_adjust' => 'price_adjust',
                    'o.prepay_amount' => 'prepay_amount',
                    'o.state' => 'state',
                    'o.memo' => 'memo',
                ))
                ->find();
            $tourId = $orderTourList['tour_id'];
            $tourInfo = M('tour')->where("id = '{$tourId}'")->field('id,name,cover_pic')->find();

            $coverPic = $tourInfo['cover_pic'];
            $coverPic = str_replace('#file1#', 'http://file.m.lydlr.com', $coverPic);
            $coverPic = Utils::GetImageUrl($coverPic, 240, 160, 1);

            $totalMoney = Utils::getYuan($orderTourList['price_total'] + $orderTourList['price_adjust']);
            $prepayAmount = Utils::getYuan($orderTourList['prepay_amount']);
            $orderTourList['start_time'] = substr($orderTourList['start_time'], 0, 10);

            $this->assign('userInfo', $userInfo);
            $this->assign('tourInfo', $tourInfo);
            $this->assign('coverPic', $coverPic);
            $this->assign('totalMoney', $totalMoney);
            $this->assign('orderTourList', $orderTourList);
            $this->assign('prepayAmount', $prepayAmount);

            $this->display();
        } else {
            $domain = $_SERVER['SERVER_NAME'];
            $url = "http://" . $domain . "/index.php";
            header("Location:" . $url);
        }
    }


    public function showFinalPayment()
    {
        $isLogin = session('isLogin');
        if ($isLogin == 'yes') {
            $_SESSION['preForumCode'] = 400;
            $userInfo = $this->userInfo;
            $M = M();

            $id = intval(I('get.id'));
            $orderTourList = $M->table('top_tour as t,top_order_tour as o')
                ->where("o.id ='{$id}'&& o.tour_id = t.id")
                ->field(array(
                    'o.id' => 'id',
                    't.name' => 'name',
                    't.cover_pic' => 'cover_pic',
                    'o.client_adult_count' => 'client_adult_count',
                    'o.client_child_count' => 'client_child_count',
                    'o.start_time' => 'start_time',
                    'o.price_total' => 'price_total',
                    'o.price_adjust' => 'price_adjust',
                    'o.prepay_amount' => 'prepay_amount',
                    'o.state' => 'state',
                    'o.memo' => 'memo',
                ))
                ->find();

            $pic = substr($orderTourList['cover_pic'], 0, 7);
            $picUrl = str_replace($pic, C('FILE1_BASE_URL'), $orderTourList['cover_pic']);
            $pic = Utils::GetImageUrl($picUrl, 240, 160, 1);

            $totalMoney = Utils::getYuan($orderTourList['price_total'] + $orderTourList['price_adjust']);
            $prepayAmount = Utils::getYuan($orderTourList['prepay_amount']);

            $preForum = $totalMoney - $prepayAmount;

            $this->assign('userInfo', $userInfo);
            $this->assign('pic', $pic);
            $this->assign('preForum', $preForum);
            $this->assign('totalMoney', $totalMoney);
            $this->assign('orderTourList', $orderTourList);
            $this->assign('prepayAmount', $prepayAmount);

            $this->display();
        } else {
            $domain = $_SERVER['SERVER_NAME'];
            $url = "http://" . $domain . "/index.php";
            header("Location:" . $url);
        }
    }



    function showOrderCancel()
    {
        $isLogin = session('isLogin');
        if ($isLogin == 'yes') {
            $_SESSION['orderCancelCode'] = 400;
            $userInfo = $this->userInfo;
            $M = M();

            $id = intval(I('get.id'));
            $orderTourList = $M->table('top_tour as t,top_order_tour as o')
                ->where("o.id ='{$id}'&& o.tour_id = t.id")
                ->field(array(
                    'o.id' => 'id',
                    't.name' => 'name',
                    't.cover_pic' => 'cover_pic',
                    'o.client_adult_count' => 'client_adult_count',
                    'o.client_child_count' => 'client_child_count',
                    'o.start_time' => 'start_time',
                    'o.price_total' => 'price_total',
                    'o.price_adjust' => 'price_adjust',
                    'o.prepay_amount' => 'prepay_amount',
                    'o.state' => 'state',
                    'o.memo' => 'memo',
                ))
                ->find();

            $pic = substr($orderTourList['cover_pic'], 0, 7);
            $picUrl = str_replace($pic, C('FILE1_BASE_URL'), $orderTourList['cover_pic']);
            $pic = Utils::GetImageUrl($picUrl, 240, 160, 1);

            $totalMoney = Utils::getYuan($orderTourList['price_total'] + $orderTourList['price_adjust']);
            $prepayAmount = Utils::getYuan($orderTourList['prepay_amount']);

            $preForum = $totalMoney - $prepayAmount;

            $this->assign('userInfo', $userInfo);
            $this->assign('pic', $pic);
            $this->assign('preForum', $preForum);
            $this->assign('totalMoney', $totalMoney);
            $this->assign('orderTourList', $orderTourList);
            $this->assign('prepayAmount', $prepayAmount);

            $this->display();
        } else {
            $domain = $_SERVER['SERVER_NAME'];
            $url = "http://" . $domain . "/index.php";
            header("Location:" . $url);
        }
    }



    public function orderCancel()
    {
        if (IS_POST && IS_AJAX) {
            $postCode = I('code');
            $code = session('orderCancelCode');

            if ($postCode == $code) {
                session('orderCancelCode', null);
                $where['id'] = I('id');
                $orderInfo = M('order_tour')->where($where)->find();

                if ($orderInfo['fullpay_time'] != '') {
                    $tourMoney = $orderInfo['price_total'] + $orderInfo['price_adjust'] - Utils::CalcCommission($orderInfo['commission_rate'], $orderInfo['price_total'] + $orderInfo['price_adjust']);
                } else {
                    $tourMoney = $orderInfo['prepay_amount'] - Utils::CalcCommission($orderInfo['commission_rate'], $orderInfo['prepay_amount']);
                }

                $providerId = $orderInfo['provider_id'];
                $operatorId = $orderInfo['provider_operator_id'];
                $providerInfo = M('provider')->where("id = '{$providerId}'")->find();

                $providerAccountInfo = M('provider_account')->where("provider_id = '{$providerId}' && operator_id = '{$operatorId}'")->find();
                $providerAccountBalance = $providerAccountInfo['account_balance'];
                $providerFrozenBalance = Utils::getProviderInOperatorFrozenFen(3, $providerId, $operatorId);
                //供应商可用余额
                $providerBalance = $providerAccountBalance - $providerFrozenBalance;

                if ($providerBalance < $tourMoney) {
                    $data['status'] = 0;
                    $data['msg'] = "订单数据同步失败, 错误代码007, 请与供应商" . $providerInfo['mobile'] . "联系";
                    $this->ajaxReturn($data);
                }

                $orderLogData['order_id'] = $orderInfo['id'];
                $orderLogData['user_id'] = $orderInfo['agency_id'];
                $orderLogData['user_name'] = $orderInfo['agency_name'];
                $orderLogData['content'] = '代理商' . $orderInfo['agency_name'] . '申请订单取消';
                $orderLogData['amount'] = 0;
                $orderLogData['payable_total'] = $tourMoney;
                $orderLogData['create_time'] = date('Y-m-d H:i:s', time());
                //向 log_order_tour 表插入记录
                $orderLogResult = M('log_order_tour')->add($orderLogData);

                $data['state'] = Top::OrderStateCanceling;
                $result = M('order_tour')->where($where)->save($data);

                if ($result && $orderLogResult) {
                    $data['status'] = 1;
                    $data['msg'] = '订单取消中';
                    $this->ajaxReturn($data);
                } else {
                    $data['status'] = 0;
                    $data['msg'] = '操作失败';
                    $this->ajaxReturn($data);
                }
            }
        }
    }


    public function allPayed()
    {
        if (IS_AJAX && IS_POST) {
            $postCode = I('code');
            $code = session('allPayedCode');

            if ($postCode == $code) {
                session('allPayedCode', null);

                //接收ajax传来的状态
                $order_data['state'] = Top::OrderStateAllPayed;
                $order_data['fullpay_time'] = date('Y-m-d H:i:s', time());

                $order_id['id'] = I('id');
                $keyid = Utils::getDecrypt(I('keyid'));

                if ($order_id['id'] != $keyid) {
                    $data['status'] = 10;
                    $data['msg'] = '支付失败';
                    $this->ajaxReturn($data);
                }

                //查找线路id
                $list = M('order_tour')->where($order_id)->find();

                $entityId = $list['agency_id'];
                $userList = M('agency')->where("id = '{$entityId}'")->find();

                //可用余额
                $availableBalance = Utils::getAgencyAvailableFen($entityId);
                //计算总价
                $totalMoneyFen = $list['price_adjust'] + $list['price_total'];

                if ($userList['account_state'] == '2') {
                    $data['status'] = 10;
                    $data['msg'] = '账户被冻结';
                    $this->ajaxReturn($data);
                }

                if ($availableBalance >= $totalMoneyFen && $list['state'] == Top::OrderStateWaitForPayment) {
                    //开启事务
                    M('operator')->startTrans();
                    try {
                        $operatorId = $userList['operator_id'];
                        $operatorInfo = M('operator')->lock(true)->where("id = '{$operatorId}'")->find();
                        $operatorState = $operatorInfo['state'];
                        $operatorCreditBalance = $operatorInfo['account_credit_balance'];

                        if ($operatorCreditBalance < $totalMoneyFen) {
                            $data['status'] = 10;
                            $data['msg'] = $operatorInfo['msg1'];
                            $this->ajaxReturn($data);
                        }

                        if ($operatorState != 1) {
                            $data['status'] = 10;
                            $data['msg'] = '运营商账户被禁用';
                            $this->ajaxReturn($data);
                        }

                        //代理商减钱,并更新 agency 表
                        $result = M('agency')->where("id = '{$entityId}'")->setDec('account_balance', $totalMoneyFen);
                        $operatorCreditBalanceResult = M('operator')->where("id = '{$operatorId}'")->setDec('account_credit_balance', $totalMoneyFen);
                        $nowTime = Utils::getBatch();
                        //查找代理商id,显示单条数据
                        $agencyList = M('agency')->where("id = '{$entityId}'")->find();

                        $agency_data['operator_id'] = $userList['operator_id'];
                        $agency_data['action'] = '支出线路产品订单金额';
                        $agency_data['entity_type'] = Top::EntityTypeAgency;
                        $agency_data['entity_id'] = $agencyList['id'];
                        $agency_data['account'] = $agencyList['account'];
                        $agency_data['sn'] = Utils::getSn();
                        $agency_data['batch'] = $nowTime;
                        $agency_data['amount'] = '-' . $totalMoneyFen;
                        $agency_data['balance'] = $agencyList['account_balance'];
                        $agency_data['create_time'] = date('Y-m-d H:i:s', time());
                        $agency_data['remark'] = 'top_order_tour.id:' . I('id');
                        $agency_data['object_id'] = I('id');
                        $agency_data['object_type'] = Top::ObjectTypeTour;
                        $agency_data['object_name'] = '线路';
                        //向 account_transaction 表插入一条代理商购买线路减钱的记录
                        $agency_delmoney = M('account_transaction')->add($agency_data);

                        $operatorList = M('operator')->where("id = '{$operatorId}'")->find();
                        $operator_data['operator_id'] = $operatorId;
                        $operator_data['action'] = '支出线路产品订单金额';
                        $operator_data['entity_type'] = Top::EntityTypeOperator;
                        $operator_data['entity_id'] = $operatorList['id'];
                        $operator_data['account'] = $operatorList['account'];
                        $operator_data['sn'] = Utils::getSn();
                        $operator_data['amount'] = '-' . $totalMoneyFen;
                        $operator_data['balance'] = $operatorList['account_credit_balance'];
                        $operator_data['create_time'] = date('Y-m-d H:i:s', time());
                        $operator_data['remark'] = 'top_order_tour.id:' . I('id');
                        $operator_data['object_id'] = I('id');
                        $operator_data['object_type'] = Top::ObjectTypeTour;
                        $operator_data['object_name'] = '线路';
                        //向 operator_credit_transaction 表插入一条运营商授信金额减钱的记录
                        $operator_delmoney = M('operator_credit_transaction')->add($operator_data);

                        $tour_id['id'] = $list['tour_id'];
                        //查询线路
                        $tour_list = M('tour')->where($tour_id)->find();

                        $where['id'] = $tour_list['provider_id'];

                        //供应商表加钱,并更新 provider 表
                        $provideInfo = M('provider')->where($where)->find();
                        $providerBalance = $provideInfo['account_balance'];
                        $providerAccountBalance['account_balance'] = $providerBalance + $totalMoneyFen;
                        $provideResult = M('provider')->where($where)->save($providerAccountBalance);

                        //将 order_tour 表订单的状态更新
                        $orderResult = M('order_tour')->where($order_id)->save($order_data);

                        $orderLogData['order_id'] = I('id');
                        $orderLogData['user_id'] = $agencyList['id'];
                        $orderLogData['user_name'] = $agencyList['name'];
                        $orderLogData['content'] = "代理商" . $orderLogData['user_name'] . "付全款,付款金额：" . Utils::getYuan($totalMoneyFen);
                        $orderLogData['create_time'] = date("Y-m-d H:i:s", time());
                        $orderLogData['amount'] = $totalMoneyFen;
                        $orderLogData['payable_total'] = $totalMoneyFen;
                        //向 log_order_tour 表插入记录
                        $orderLogResult = M('log_order_tour')->add($orderLogData);

                        //查找供应商id，显示单条记录
                        $providerList = M('provider')->where($where)->find();
                        $agencyOperatorId = $userList['operator_id'];

                        //new add
                        $providerId = $providerList['id'];
                        $providerAccountInfo = M('provider_account')->where("provider_id = '{$providerId}' && operator_id = '{$agencyOperatorId}'")->find();

                        if ($providerAccountInfo) {
                            $providerAccountResult = M('provider_account')->where("provider_id = '{$providerId}' && operator_id = '{$agencyOperatorId}'")->setInc('account_balance', $totalMoneyFen);
                        } else {
                            $providerAccountData['provider_name'] = $providerList['name'];
                            $providerAccountData['provider_id'] = $providerId;
                            $providerAccountData['operator_id'] = $agencyOperatorId;
                            $providerAccountData['account'] = Utils::getNextAccount(Top::EntityTypeProvider, $agencyOperatorId);
                            $providerAccountData['account_balance'] = $totalMoneyFen;
                            $providerAccountData['create_time'] = date("Y-m-d H:i:s", time());
                            $providerAccountResult = M('provider_account')->add($providerAccountData);
                        }

                        $providerAccountNewInfo = M('provider_account')->where("provider_id = '{$providerId}' && operator_id = '{$agencyOperatorId}'")->find();
                        $provider_account_data['operator_id'] = $providerList['operator_id'];
                        $provider_account_data['action'] = '收入线路产品订单金额';
                        $provider_account_data['entity_id'] = $providerAccountNewInfo['provider_id'];
                        $provider_account_data['entity_type'] = Top::EntityTypeProvider;
                        $provider_account_data['account'] = $providerAccountNewInfo['account'];
                        $provider_account_data['sn'] = Utils::getSn();
                        $provider_account_data['batch'] = $nowTime;
                        $provider_account_data['amount'] = $totalMoneyFen;
                        $provider_account_data['create_time'] = date('Y-m-d H:i:s', time());
                        $provider_account_data['balance'] = $providerAccountNewInfo['account_balance'];
                        $provider_account_data['remark'] = 'top_order_tour.id:' . I('id');
                        $provider_account_data['object_id'] = I('id');
                        $provider_account_data['object_type'] = Top::ObjectTypeTour;
                        $provider_account_data['object_name'] = '线路';
                        //向 account_transaction 表插入一条供应商增钱的记录
                        $provider_account_addmoney = M('account_transaction')->add($provider_account_data);
                        //end

                        //$providerAddmoneyInfo = M('account_transaction')->where("id = '{$provider_account_addmoney}'")->field('id,sn')->find();
                        $agencyName = $agencyList['name'];
                        $tourName = $tour_list['name'];
                        $content = $agencyName . "已为" . $tourName . "订单付全款";
                        Sms::Send($tour_list['contact_phone'], $content, $this->cdkey, $this->pwd, $this->signature, $this->smsOperatorId);

                        $userInfo = M('user')->where("id = " . $tour_list['user_id'])->find();
                        $notifyMsgTypes = explode(",", $userInfo['notify_msg_types']);
                        array_shift($notifyMsgTypes);
                        array_pop($notifyMsgTypes);
                        $transactionMessage = $notifyMsgTypes[1];

                        $template = array(
                            'touser' => $userInfo['weixinmp_openid'],
                            'template_id' => Utils::orderPaySuccessTemplateId(),

                            'data' => array(
                                'first' => array('value' => urlencode($content), 'color' => "#000"),
                                'keyword1' => array('value' => urlencode($list['order_sn']), 'color' => "#000"),
                                'keyword2' => array('value' => urlencode('全款'), 'color' => '#000'),
                                'keyword3' => array('value' => urlencode($list['tour_name']), 'color' => '#000'),
                                'keyword4' => array('value' => urlencode(Utils::getYuan($totalMoneyFen)), 'color' => '#000'),
                                'keyword5' => array('value' => urlencode(date('Y-m-d H:i:s', time())), 'color' => '#000'),
                                'remark' => array('value' => urlencode(''), 'color' => '#000'),
                            )
                        );

                        if ($transactionMessage) {
                            $this->send_tpl($template);
                        }

                        if ($providerList['commission_rate'] != '' && $providerList['commission_rate'] != null && $list['commission_rate'] != 0) {
                            //计算出佣金
                            $commission_rate = $list['commission_rate'];
                            $commissionFen = Utils::CalcCommission($commission_rate, $totalMoneyFen);
                            //将减少佣金金额后的总金额更新 provider 表
                            $providerAccount = M('provider')->where($where)->setDec('account_balance', $commissionFen);

                            //查找供应商ID信息
                            $provider_rate_list = M('provider')->where($where)->find();

                            //new add
                            $providerAccountDecResult = M('provider_account')->where("provider_id = '{$providerId}' && operator_id = '{$agencyOperatorId}'")->setDec('account_balance', $commissionFen);
                            $providerAccountNewDecInfo = M('provider_account')->where("provider_id = '{$providerId}' && operator_id = '{$agencyOperatorId}'")->find();
                            $provider_account_rate_data['operator_id'] = $provider_rate_list['operator_id'];
                            $provider_account_rate_data['action'] = '支出线路产品订单佣金';
                            $provider_account_rate_data['entity_id'] = $providerAccountNewDecInfo['provider_id'];
                            $provider_account_rate_data['balance'] = $providerAccountNewDecInfo['account_balance'];
                            $provider_account_rate_data['entity_type'] = Top::EntityTypeProvider;
                            $provider_account_rate_data['amount'] = '-' . $commissionFen;
                            $provider_account_rate_data['account'] = $providerAccountNewDecInfo['account'];
                            $provider_account_rate_data['sn'] = Utils::getSn();
                            $provider_account_rate_data['batch'] = $nowTime;
                            $provider_account_rate_data['create_time'] = date('Y-m-d H:i:s', time());
                            $provider_account_rate_data['balance'] = $providerAccountNewDecInfo['account_balance'];
                            $provider_account_rate_data['remark'] = 'top_order_tour.id:' . I('id');
                            $provider_account_rate_data['object_id'] = I('id');
                            $provider_account_rate_data['object_type'] = Top::ObjectTypeTour;
                            $provider_account_rate_data['object_name'] = '线路';
                            //向 account_transaction 表插入一条供应商减钱的记录
                            $provider_account_rate_delmoney = M('account_transaction')->add($provider_account_rate_data);
                            //end

                            $sys_list = M('sys')->where("id = 1")->find();
                            $sys_data['account_balance'] = $sys_list['account_balance'];
                            $sys_data['update_time'] = date('Y-m-d H:i:s', time());
                            $sys_data['account_balance'] = $commissionFen + $sys_data['account_balance'];
                            //将一条系统增加佣金金额的信息更新 sys 表
                            $sys = M('sys')->where("id = 1")->save($sys_data);

                            $sys_list = M('sys')->where("id = 1")->find();

                            $sys_account_data['operator_id'] = 0;
                            $sys_account_data['action'] = '收入线路产品订单佣金';
                            $sys_account_data['entity_type'] = Top::EntityTypeSystem;
                            $sys_account_data['entity_id'] = $sys_list['id'];
                            $sys_account_data['account'] = $sys_list['account'];
                            $sys_account_data['balance'] = $sys_list['account_balance'];
                            $sys_account_data['sn'] = Utils::getSn();
                            $sys_account_data['batch'] = $nowTime;
                            $sys_account_data['amount'] = $commissionFen;
                            $sys_account_data['create_time'] = date('Y-m-d H:i:s', time());
                            $sys_account_data['balance'] = $sys_list['account_balance'];
                            $sys_account_data['remark'] = 'top_order_tour.id:' . I('id');
                            $sys_account_data['object_id'] = I('id');
                            $sys_account_data['object_type'] = Top::ObjectTypeTour;
                            $sys_account_data['object_name'] = '线路';
                            //向 account_transaction 表插入一条运营商增加金额的信息
                            $sys_account_list = M('account_transaction')->add($sys_account_data);

                            $operator_account_data['operator_id'] = $operatorList['id'];
                            $operator_account_data['transaction_type'] = 1;
                            $operator_account_data['profit_rate'] = $operatorList['profit_rate'];
                            $operator_account_data['action'] = '收入线路产品订单佣金';
                            $operator_account_data['entity_type'] = Top::EntityTypeOperator;
                            $operator_account_data['entity_id'] = $operatorList['id'];
                            $operator_account_data['account'] = $operatorList['account'];
                            $operator_account_data['balance'] = $operatorList['account_balance'];
                            $operator_account_data['sn'] = Utils::getSn();
                            $operator_account_data['batch'] = $nowTime;
                            $operator_account_data['amount'] = $commissionFen;
                            $operator_account_data['create_time'] = date('Y-m-d H:i:s', time());
                            $operator_account_data['balance'] = $operatorList['account_balance'];
                            $operator_account_data['remark'] = 'top_order_tour.id:' . I('id');
                            $operator_account_data['object_id'] = I('id');
                            $operator_account_data['object_type'] = Top::ObjectTypeTour;
                            $operator_account_data['object_name'] = '线路';
                            //向 account_transaction 表插入一条运营商增加金额的信息
                            $operator_account_list = M('account_transaction')->add($operator_account_data);

                            $skuId = $list['tour_sku_id'];
                            //查询 tour_sku 表
                            $skuList = M('tour_sku')->where("id = '{$skuId}'")->find();
                            $clientTotal = $list['client_total'];
                            $skuNum = $skuList['sku'];
                            //计算卖出多少位控
                            $skuNum = $skuNum - $clientTotal;
                            //更新
                            $skuResult = M('tour_sku')->execute("update top_tour_sku set sku = '{$skuNum}' where id = '{$skuId}'");
                        }

                        if ($result && $agency_delmoney && $provideResult && $orderResult && $orderLogResult && $providerAccountResult && $provider_account_addmoney && $operatorCreditBalanceResult && $operator_delmoney) {
                            M('operator')->commit();
                            $data['status'] = 1;
                            $this->ajaxReturn($data);
                        }
                    } catch (Exception $ex) {
                        M('operator')->rollback();
                    }
                } else {
                    $data['status'] = 0;
                    $this->ajaxReturn($data);
                }
            } else {
                $data['status'] = 3;
                $this->ajaxReturn($data);
            }
        }
    }


    public function prePayed()
    {
        if (IS_AJAX && IS_POST) {
            $postCode = I('code');
            $code = session('prePayedCode');

            if ($postCode == $code) {
                session('prePayedCode', null);
                //接收ajax传来的状态
                $order_data['state'] = Top::OrderStatePrepayed;
                $order_data['prepay_time'] = date('Y-m-d H:i:s', time());
                $order_id['id'] = I('id');
                $keyid = Utils::getDecrypt(I('keyid'));

                if ($order_id['id'] != $keyid) {
                    $data['status'] = 10;
                    $data['msg'] = '支付失败';
                    $this->ajaxReturn($data);
                }

                //查找线路id
                $list = M('order_tour')->where($order_id)->find();

                $entityId = $list['agency_id'];
                $userList = M('agency')->where("id = '{$entityId}'")->find();
                //可用余额
                $availableBalance = Utils::getAgencyAvailableFen($entityId);

                //计算总价
                $prePayedMoney = intval($list['prepay_amount']);

                if ($userList['account_state'] == '2') {
                    $data['status'] = 10;
                    $data['msg'] = '账户被冻结';
                    $this->ajaxReturn($data);
                }

                if ($availableBalance >= $prePayedMoney && $list['state'] == Top::OrderStateWaitForPayment) {
                    //查找代理商id,显示单条数据
                    $agencyList = M('agency')->where("id = '{$entityId}'")->find();
                    $agencyAccountBalance = $agencyList['account_balance'];
                    //计算
                    $agencyAccountBalance = $agencyAccountBalance - $prePayedMoney;
                    M('operator')->startTrans();
                    try {
                        $operatorId = $userList['operator_id'];
                        $operatorInfo = M('operator')->lock(true)->where("id = '{$operatorId}'")->find();
                        $operatorState = $operatorInfo['state'];
                        $operatorCreditBalance = $operatorInfo['account_credit_balance'];

                        if ($operatorCreditBalance < $prePayedMoney) {
                            $data['status'] = 10;
                            $data['msg'] = $operatorInfo['msg1'];
                            $this->ajaxReturn($data);
                        }

                        if ($operatorState != 1) {
                            $data['status'] = 10;
                            $data['msg'] = '运营商账户被禁用';
                            $this->ajaxReturn($data);
                        }
                        //代理商减钱,并更新 agency 表
                        $result = M('agency')->execute("update top_agency set account_balance = '{$agencyAccountBalance}' where id = '{$entityId}'");
                        $operatorCreditBalanceResult = M('operator')->where("id = '{$operatorId}'")->setDec('account_credit_balance', $prePayedMoney);

                        $nowTime = Utils::getBatch();
                        $agency_data['operator_id'] = $userList['operator_id'];
                        $agency_data['action'] = '支出线路产品订单金额';
                        $agency_data['entity_type'] = Top::EntityTypeAgency;
                        $agency_data['entity_id'] = $agencyList['id'];
                        $agency_data['amount'] = -$prePayedMoney;
                        $agency_data['account'] = $agencyList['account'];
                        $agency_data['sn'] = Utils::getSn();
                        $agency_data['batch'] = $nowTime;
                        $agency_data['create_time'] = date('Y-m-d H:i:s', time());
                        $agency_data['balance'] = $agencyAccountBalance;
                        $agency_data['remark'] = 'top_order_tour.id:' . I('id');
                        $agency_data['object_id'] = I('id');
                        $agency_data['object_type'] = Top::ObjectTypeTour;
                        $agency_data['object_name'] = '线路';
                        //向 account_transaction 表插入一条代理商购买线路减钱的记录
                        $agency_delmoney = M('account_transaction')->add($agency_data);

                        $operatorList = M('operator')->where("id = '{$operatorId}'")->find();
                        $operator_data['operator_id'] = $operatorId;
                        $operator_data['action'] = '支出线路产品订单金额';
                        $operator_data['entity_type'] = Top::EntityTypeOperator;
                        $operator_data['entity_id'] = $operatorList['id'];
                        $operator_data['account'] = $operatorList['account'];
                        $operator_data['sn'] = Utils::getSn();
                        $operator_data['amount'] = '-' . $prePayedMoney;
                        $operator_data['balance'] = $operatorList['account_credit_balance'];
                        $operator_data['create_time'] = date('Y-m-d H:i:s', time());
                        $operator_data['remark'] = 'top_order_tour.id:' . I('id');
                        $operator_data['object_id'] = I('id');
                        $operator_data['object_type'] = Top::ObjectTypeTour;
                        $operator_data['object_name'] = '线路';
                        //向 operator_credit_transaction 表插入一条运营商授信金额减钱的记录
                        $operator_delmoney = M('operator_credit_transaction')->add($operator_data);

                        $tour_id['id'] = $list['tour_id'];
                        //查询线路
                        $tour_list = M('tour')->where($tour_id)->find();

                        $where['id'] = $tour_list['provider_id'];

                        $providerId = $tour_list['provider_id'];
                        $providerInfo = M('provider')->where($where)->find();
                        $providerBalance = $providerInfo['account_balance'];
                        //计算
                        $providerAccountBalance = $providerBalance + $prePayedMoney;
                        //供应商表加钱,并更新 provider 表
                        $provider_result = M('provider')->execute("update top_provider set account_balance = '{$providerAccountBalance}' where id = '{$providerId}'");

                        //将 order_tour 表订单的状态更新
                        $orderResult = M('order_tour')->where($order_id)->save($order_data);

                        $orderLogData['order_id'] = I('id');
                        $orderLogData['user_id'] = $agencyList['id'];
                        $orderLogData['user_name'] = $agencyList['name'];
                        $orderLogData['content'] = "代理商" . $orderLogData['user_name'] . "付预付款,预付金额：" . Utils::getYuan($prePayedMoney);
                        $orderLogData['create_time'] = date("Y-m-d H:i:s", time());
                        $orderLogData['amount'] = $prePayedMoney;
                        $orderLogData['payable_total'] = intval($list['price_adjust'] + $list['price_total']);
                        //向 log_order_tour 表插入记录
                        $orderLogResult = M('log_order_tour')->add($orderLogData);

                        //查找供应商id，显示单条记录
                        $providerList = M('provider')->where($where)->find();

                        //new add
                        $agencyOperatorId = $userList['operator_id'];

                        $providerId = $providerList['id'];
                        $providerAccountInfo = M('provider_account')->where("provider_id = '{$providerId}' && operator_id = '{$agencyOperatorId}'")->find();

                        if ($providerAccountInfo) {
                            $providerAccountResult = M('provider_account')->where("provider_id = '{$providerId}' && operator_id = '{$agencyOperatorId}'")->setInc('account_balance', $prePayedMoney);
                        } else {
                            $providerAccountData['provider_name'] = $providerList['name'];
                            $providerAccountData['provider_id'] = $providerId;
                            $providerAccountData['operator_id'] = $agencyOperatorId;
                            $providerAccountData['account'] = Utils::getNextAccount(Top::EntityTypeProvider, $agencyOperatorId);
                            $providerAccountData['account_balance'] = $prePayedMoney;
                            $providerAccountData['create_time'] = date("Y-m-d H:i:s", time());
                            $providerAccountResult = M('provider_account')->add($providerAccountData);
                        }

                        $providerAccountNewInfo = M('provider_account')->where("provider_id = '{$providerId}' && operator_id = '{$agencyOperatorId}'")->find();
                        $provider_account_data['operator_id'] = $providerList['operator_id'];
                        $provider_account_data['action'] = '收入线路产品订单金额';
                        $provider_account_data['entity_id'] = $providerAccountNewInfo['provider_id'];
                        $provider_account_data['entity_type'] = Top::EntityTypeProvider;
                        $provider_account_data['account'] = $providerAccountNewInfo['account'];
                        $provider_account_data['sn'] = Utils::getSn();
                        $provider_account_data['batch'] = $nowTime;
                        $provider_account_data['amount'] = $prePayedMoney;
                        $provider_account_data['create_time'] = date('Y-m-d H:i:s', time());
                        $provider_account_data['balance'] = $providerAccountNewInfo['account_balance'];
                        $provider_account_data['remark'] = 'top_order_tour.id:' . I('id');
                        $provider_account_data['object_id'] = I('id');
                        $provider_account_data['object_type'] = Top::ObjectTypeTour;
                        $provider_account_data['object_name'] = '线路';
                        //向 account_transaction 表插入一条供应商增钱的记录
                        $provider_account_addmoney = M('account_transaction')->add($provider_account_data);
                        //end

                        //$providerAddmoneyInfo = M('account_transaction')->where("id = '{$provider_account_addmoney}'")->field('id,sn')->find();
                        $agencyName = $agencyList['name'];
                        $tourName = $tour_list['name'];
                        $content = $agencyName . "已为" . $tourName . "订单付预付款";
                        Sms::Send($tour_list['contact_phone'], $content, $this->cdkey, $this->pwd, $this->signature, $this->smsOperatorId);

                        $userInfo = M('user')->where("id = " . $tour_list['user_id'])->find();
                        $notifyMsgTypes = explode(",", $userInfo['notify_msg_types']);
                        array_shift($notifyMsgTypes);
                        array_pop($notifyMsgTypes);
                        $transactionMessage = $notifyMsgTypes[1];

                        $template = array(
                            'touser' => $userInfo['weixinmp_openid'],
                            'template_id' => Utils::orderPaySuccessTemplateId(),

                            'data' => array(
                                'first' => array('value' => urlencode($content), 'color' => "#000"),
                                'keyword1' => array('value' => urlencode($list['order_sn']), 'color' => "#000"),
                                'keyword2' => array('value' => urlencode('预付款'), 'color' => '#000'),
                                'keyword3' => array('value' => urlencode($list['tour_name']), 'color' => '#000'),
                                'keyword4' => array('value' => urlencode(Utils::getYuan($prePayedMoney)), 'color' => '#000'),
                                'keyword5' => array('value' => urlencode(date('Y-m-d H:i:s', time())), 'color' => '#000'),
                                'remark' => array('value' => urlencode(''), 'color' => '#000'),
                            )
                        );

                        if ($transactionMessage) {
                            $this->send_tpl($template);
                        }

                        if ($providerList['commission_rate'] != '' && $providerList['commission_rate'] != null && $list['commission_rate'] != 0) {
                            //计算出佣金
                            $commission_rate = $list['commission_rate'];
                            $commissionFen = Utils::CalcCommission($commission_rate, $prePayedMoney);
                            //将减少佣金金额后的总金额更新 provider 表
                            $providerAccount = M('provider')->where($where)->setDec('account_balance', $commissionFen);
                            //查找供应商ID信息
                            $provider_rate_list = M('provider')->where($where)->find();

                            //new add
                            $providerAccountDecResult = M('provider_account')->where("provider_id = '{$providerId}' && operator_id = '{$agencyOperatorId}'")->setDec('account_balance', $commissionFen);
                            $providerAccountNewDecInfo = M('provider_account')->where("provider_id = '{$providerId}' && operator_id = '{$agencyOperatorId}'")->find();
                            $provider_account_rate_data['operator_id'] = $provider_rate_list['operator_id'];
                            $provider_account_rate_data['action'] = '支出线路产品订单佣金';
                            $provider_account_rate_data['entity_id'] = $providerAccountNewDecInfo['provider_id'];
                            $provider_account_rate_data['balance'] = $providerAccountNewDecInfo['account_balance'];
                            $provider_account_rate_data['entity_type'] = Top::EntityTypeProvider;
                            $provider_account_rate_data['amount'] = '-' . $commissionFen;
                            $provider_account_rate_data['account'] = $providerAccountNewDecInfo['account'];
                            $provider_account_rate_data['sn'] = Utils::getSn();
                            $provider_account_rate_data['batch'] = $nowTime;
                            $provider_account_rate_data['create_time'] = date('Y-m-d H:i:s', time());
                            $provider_account_rate_data['balance'] = $providerAccountNewDecInfo['account_balance'];
                            $provider_account_rate_data['remark'] = 'top_order_tour.id:' . I('id');
                            $provider_account_rate_data['object_id'] = I('id');
                            $provider_account_rate_data['object_type'] = Top::ObjectTypeTour;
                            $provider_account_rate_data['object_name'] = '线路';
                            //向 account_transaction 表插入一条供应商减钱的记录
                            $provider_account_rate_delmoney = M('account_transaction')->add($provider_account_rate_data);
                            //end

                            $sys_list = M('sys')->where("id = 1")->find();
                            $sys_data['account_balance'] = $sys_list['account_balance'];
                            $sys_data['update_time'] = date('Y-m-d H:i:s', time());
                            $sys_data['account_balance'] = $commissionFen + $sys_data['account_balance'];
                            //将一条系统增加佣金金额的信息更新 sys 表
                            $sys = M('sys')->where("id = 1")->save($sys_data);

                            $sys_list = M('sys')->where("id = 1")->find();

                            $sys_account_data['operator_id'] = 0;
                            $sys_account_data['action'] = '收入线路产品订单佣金';
                            $sys_account_data['entity_type'] = Top::EntityTypeSystem;
                            $sys_account_data['entity_id'] = $sys_list['id'];
                            $sys_account_data['account'] = $sys_list['account'];
                            $sys_account_data['balance'] = $sys_list['account_balance'];
                            $sys_account_data['sn'] = Utils::getSn();
                            $sys_account_data['batch'] = $nowTime;
                            $sys_account_data['amount'] = $commissionFen;
                            $sys_account_data['create_time'] = date('Y-m-d H:i:s', time());
                            $sys_account_data['balance'] = $sys_list['account_balance'];
                            $sys_account_data['remark'] = 'top_order_tour.id:' . I('id');
                            $sys_account_data['object_id'] = I('id');
                            $sys_account_data['object_type'] = Top::ObjectTypeTour;
                            $sys_account_data['object_name'] = '线路';
                            //向 account_transaction 表插入一条运营商增加金额的信息
                            $sys_account_list = M('account_transaction')->add($sys_account_data);

                            $operator_account_data['operator_id'] = $operatorList['id'];
                            $operator_account_data['transaction_type'] = 1;
                            $operator_account_data['profit_rate'] = $operatorList['profit_rate'];
                            $operator_account_data['action'] = '收入线路产品订单佣金';
                            $operator_account_data['entity_type'] = Top::EntityTypeOperator;
                            $operator_account_data['entity_id'] = $operatorList['id'];
                            $operator_account_data['account'] = $operatorList['account'];
                            $operator_account_data['amount'] = $commissionFen;
                            $operator_account_data['sn'] = Utils::getSn();
                            $operator_account_data['batch'] = $nowTime;
                            $operator_account_data['create_time'] = date('Y-m-d H:i:s', time());
                            $operator_account_data['balance'] = $operatorList['account_balance'];
                            $operator_account_data['remark'] = 'top_order_tour.id:' . I('id');
                            $operator_account_data['object_id'] = I('id');
                            $operator_account_data['object_type'] = Top::ObjectTypeTour;
                            $operator_account_data['object_name'] = '线路';
                            //向 account_transaction 表插入一条运营商增加金额的信息
                            $operator_account_list = M('account_transaction')->add($operator_account_data);

                            $skuId = $list['tour_sku_id'];
                            //查询 tour_sku 表
                            $skuList = M('tour_sku')->where("id = '{$skuId}'")->find();
                            $clientTotal = $list['client_total'];
                            $skuNum = $skuList['sku'];
                            //计算卖出多少位控
                            $skuNum = $skuNum - $clientTotal;
                            //更新
                            $skuResult = M('tour_sku')->execute("update top_tour_sku set sku = '{$skuNum}' where id = '{$skuId}'");
                        }
                        if ($result && $agency_delmoney && $provider_result && $orderResult && $orderLogResult && $providerAccountResult && $provider_account_addmoney && $operatorCreditBalanceResult && $operator_delmoney) {
                            M('operator')->commit();
                            $data['status'] = 1;
                            $this->ajaxReturn($data);
                        }
                    } catch (Exception $ex) {
                        M('operator')->rollback();
                    }
                } else {
                    $data['status'] = 0;
                    $this->ajaxReturn($data);
                }
            } else {
                $data['status'] = 3;
                $this->ajaxReturn($data);
            }
        }
    }


    public function preForum()
    {
        if (IS_AJAX && IS_POST) {
            $postCode = I('code');
            $code = session('preForumCode');

            if ($postCode == $code) {
                session('preForumCode', null);
                //接收ajax传来的状态
                $order_data['state'] = Top::OrderStateAllPayed;
                $order_data['fullpay_time'] = date('Y-m-d H:i:s', time());
                $order_id['id'] = I('id');
                $keyid = Utils::getDecrypt(I('keyid'));

                if ($order_id['id'] != $keyid) {
                    $data['status'] = 10;
                    $data['msg'] = '支付失败';
                    $this->ajaxReturn($data);
                }

                //查找线路id
                $list = M('order_tour')->where($order_id)->find();

                $entityId = $list['agency_id'];
                $userList = M('agency')->where("id = '{$entityId}'")->find();
                //可用余额
                $availableBalance = Utils::getAgencyAvailableFen($entityId);

                //计算总价
                $prePayedMoney = $list['price_total'] + $list['price_adjust'] - $list['prepay_amount'];

                if ($prePayedMoney == 0) {
                    $result = M('order_tour')->where($order_id)->save($order_data);

                    if ($result) {
                        $data['status'] = 1;
                        $this->ajaxReturn($data);
                    }
                }

                if ($userList['account_state'] == '2') {
                    $data['status'] = 10;
                    $data['msg'] = '账户被冻结';
                    $this->ajaxReturn($data);
                }

                if ($availableBalance >= $prePayedMoney && $list['state'] == Top::OrderStatePrepayed) {
                    //查找代理商id,显示单条数据
                    $agencyList = M('agency')->where("id = '{$entityId}'")->find();
                    $agencyAccountBalance = intval($agencyList['account_balance']);
                    //计算
                    $agencyAccountBalance = $agencyAccountBalance - $prePayedMoney;
                    M('operator')->startTrans();
                    try {
                        $operatorId = $userList['operator_id'];
                        $operatorInfo = M('operator')->lock(true)->where("id = '{$operatorId}'")->find();
                        $operatorState = $operatorInfo['state'];
                        $operatorCreditBalance = $operatorInfo['account_credit_balance'];

                        if ($operatorCreditBalance < $prePayedMoney) {
                            $data['status'] = 10;
                            $data['msg'] = $operatorInfo['msg1'];
                            $this->ajaxReturn($data);
                        }

                        if ($operatorState != 1) {
                            $data['status'] = 10;
                            $data['msg'] = '运营商账户被禁用';
                            $this->ajaxReturn($data);
                        }

                        //代理商减钱,并更新 agency 表
                        $result = M('agency')->where("id = '{$entityId}'")->setDec('account_balance', $prePayedMoney);
                        $operatorCreditBalanceResult = M('operator')->where("id = '{$operatorId}'")->setDec('account_credit_balance', $prePayedMoney);

                        $nowTime = Utils::getBatch();
                        $agency_data['operator_id'] = $userList['operator_id'];
                        $agency_data['action'] = '支出线路产品订单金额';
                        $agency_data['entity_type'] = Top::EntityTypeAgency;
                        $agency_data['entity_id'] = $agencyList['id'];
                        $agency_data['amount'] = -$prePayedMoney;
                        $agency_data['account'] = $agencyList['account'];
                        $agency_data['sn'] = Utils::getSn();
                        $agency_data['batch'] = $nowTime;
                        $agency_data['create_time'] = date('Y-m-d H:i:s', time());
                        $agency_data['balance'] = $agencyAccountBalance;
                        $agency_data['remark'] = 'top_order_tour.id:' . I('id');
                        $agency_data['object_id'] = I('id');
                        $agency_data['object_type'] = Top::ObjectTypeTour;
                        $agency_data['object_name'] = '线路';
                        //向 account_transaction 表插入一条代理商购买线路减钱的记录
                        $agency_delmoney = M('account_transaction')->add($agency_data);

                        $operatorList = M('operator')->where("id = '{$operatorId}'")->find();
                        $operator_data['operator_id'] = $operatorId;
                        $operator_data['action'] = '支出线路产品订单金额';
                        $operator_data['entity_type'] = Top::EntityTypeOperator;
                        $operator_data['entity_id'] = $operatorList['id'];
                        $operator_data['account'] = $operatorList['account'];
                        $operator_data['sn'] = Utils::getSn();
                        $operator_data['amount'] = '-' . $prePayedMoney;
                        $operator_data['balance'] = $operatorList['account_credit_balance'];
                        $operator_data['create_time'] = date('Y-m-d H:i:s', time());
                        $operator_data['remark'] = 'top_order_tour.id:' . I('id');
                        $operator_data['object_id'] = I('id');
                        $operator_data['object_type'] = Top::ObjectTypeTour;
                        $operator_data['object_name'] = '线路';
                        //向 operator_credit_transaction 表插入一条运营商授信金额减钱的记录
                        $operator_delmoney = M('operator_credit_transaction')->add($operator_data);


                        $tour_id['id'] = $list['tour_id'];
                        //查询线路
                        $tour_list = M('tour')->where($tour_id)->find();
                        $where['id'] = $tour_list['provider_id'];

                        $providerId = $tour_list['provider_id'];
                        $providerInfo = M('provider')->where($where)->find();
                        $providerBalance = $providerInfo['account_balance'];
                        //计算
                        $providerAccountBalance = $providerBalance + $prePayedMoney;
                        //供应商表加钱,并更新 provider 表
                        $provider_result = M('provider')->execute("update top_provider set account_balance = '{$providerAccountBalance}' where id = '{$providerId}'");

                        //将 order_tour 表订单的状态更新
                        $orderResult = M('order_tour')->where($order_id)->save($order_data);

                        $orderLogData['order_id'] = I('id');
                        $orderLogData['user_id'] = $agencyList['id'];
                        $orderLogData['user_name'] = $agencyList['name'];
                        $orderLogData['content'] = "代理商" . $orderLogData['user_name'] . "付尾款,尾款金额：" . Utils::getYuan($prePayedMoney);
                        $orderLogData['create_time'] = date("Y-m-d H:i:s", time());
                        $orderLogData['amount'] = $prePayedMoney;
                        $orderLogData['payable_total'] = intval($list['price_adjust'] + $list['price_total']);
                        //向 log_order_tour 表插入记录
                        $orderLogResult = M('log_order_tour')->add($orderLogData);

                        //查找供应商id，显示单条记录
                        $providerList = M('provider')->where($where)->find();

                        //new add
                        $agencyOperatorId = $userList['operator_id'];

                        $providerId = $providerList['id'];
                        $providerAccountInfo = M('provider_account')->where("provider_id = '{$providerId}' && operator_id = '{$agencyOperatorId}'")->find();

                        if ($providerAccountInfo) {
                            $providerAccountResult = M('provider_account')->where("provider_id = '{$providerId}' && operator_id = '{$agencyOperatorId}'")->setInc('account_balance', $prePayedMoney);
                        } else {
                            $providerAccountData['provider_name'] = $providerList['name'];
                            $providerAccountData['provider_id'] = $providerId;
                            $providerAccountData['operator_id'] = $agencyOperatorId;
                            $providerAccountData['account'] = Utils::getNextAccount(Top::EntityTypeProvider, $agencyOperatorId);
                            $providerAccountData['account_balance'] = $prePayedMoney;
                            $providerAccountData['create_time'] = date("Y-m-d H:i:s", time());
                            $providerAccountResult = M('provider_account')->add($providerAccountData);
                        }

                        $providerAccountNewInfo = M('provider_account')->where("provider_id = '{$providerId}' && operator_id = '{$agencyOperatorId}'")->find();
                        $provider_account_data['operator_id'] = $providerList['operator_id'];
                        $provider_account_data['action'] = '收入线路产品订单金额';
                        $provider_account_data['entity_id'] = $providerAccountNewInfo['provider_id'];
                        $provider_account_data['entity_type'] = Top::EntityTypeProvider;
                        $provider_account_data['account'] = $providerAccountNewInfo['account'];
                        $provider_account_data['sn'] = Utils::getSn();
                        $provider_account_data['batch'] = $nowTime;
                        $provider_account_data['amount'] = $prePayedMoney;
                        $provider_account_data['create_time'] = date('Y-m-d H:i:s', time());
                        $provider_account_data['balance'] = $providerAccountNewInfo['account_balance'];
                        $provider_account_data['remark'] = 'top_order_tour.id:' . I('id');
                        $provider_account_data['object_id'] = I('id');
                        $provider_account_data['object_type'] = Top::ObjectTypeTour;
                        $provider_account_data['object_name'] = '线路';
                        //向 account_transaction 表插入一条供应商增钱的记录
                        $provider_account_addmoney = M('account_transaction')->add($provider_account_data);
                        //end

                        //$providerAddmoneyInfo = M('account_transaction')->where("id = '{$provider_account_addmoney}'")->field('id,sn')->find();
                        $agencyName = $agencyList['name'];
                        $tourName = $tour_list['name'];
                        $content = $agencyName . "已为" . $tourName . "订单付尾款";
                        Sms::Send($tour_list['contact_phone'], $content, $this->cdkey, $this->pwd, $this->signature, $this->smsOperatorId);

                        $userInfo = M('user')->where("id = " . $tour_list['user_id'])->find();
                        $notifyMsgTypes = explode(",", $userInfo['notify_msg_types']);
                        array_shift($notifyMsgTypes);
                        array_pop($notifyMsgTypes);
                        $transactionMessage = $notifyMsgTypes[1];
                        $template = array(
                            'touser' => $userInfo['weixinmp_openid'],
                            'template_id' => Utils::orderPaySuccessTemplateId(),

                            'data' => array(
                                'first' => array('value' => urlencode($content), 'color' => "#000"),
                                'keyword1' => array('value' => urlencode($list['order_sn']), 'color' => "#000"),
                                'keyword2' => array('value' => urlencode('尾款'), 'color' => '#000'),
                                'keyword3' => array('value' => urlencode($list['tour_name']), 'color' => '#000'),
                                'keyword4' => array('value' => urlencode(Utils::getYuan($prePayedMoney)), 'color' => '#000'),
                                'keyword5' => array('value' => urlencode(date('Y-m-d H:i:s', time())), 'color' => '#000'),
                                'remark' => array('value' => urlencode(''), 'color' => '#000'),
                            )
                        );

                        if ($transactionMessage) {
                            $this->send_tpl($template);
                        }

                        if ($providerList['commission_rate'] != '' && $providerList['commission_rate'] != null && $list['commission_rate'] != 0) {
                            //计算出佣金
                            $commission_rate = $list['commission_rate'];
                            $commissionFen = Utils::CalcCommission($commission_rate, $prePayedMoney);

                            //将减少佣金金额后的总金额更新 provider 表
                            $providerAccount = M('provider')->where($where)->setDec('account_balance', $commissionFen);
                            //查找供应商ID信息
                            $provider_rate_list = M('provider')->where($where)->find();

                            //new add
                            $providerAccountDecResult = M('provider_account')->where("provider_id = '{$providerId}' && operator_id = '{$agencyOperatorId}'")->setDec('account_balance', $commissionFen);
                            $providerAccountNewDecInfo = M('provider_account')->where("provider_id = '{$providerId}' && operator_id = '{$agencyOperatorId}'")->find();
                            $provider_account_rate_data['operator_id'] = $provider_rate_list['operator_id'];
                            $provider_account_rate_data['action'] = '支出线路产品订单佣金';
                            $provider_account_rate_data['entity_id'] = $providerAccountNewDecInfo['provider_id'];
                            $provider_account_rate_data['balance'] = $providerAccountNewDecInfo['account_balance'];
                            $provider_account_rate_data['entity_type'] = Top::EntityTypeProvider;
                            $provider_account_rate_data['amount'] = '-' . $commissionFen;
                            $provider_account_rate_data['account'] = $providerAccountNewDecInfo['account'];
                            $provider_account_rate_data['sn'] = Utils::getSn();
                            $provider_account_rate_data['batch'] = $nowTime;
                            $provider_account_rate_data['create_time'] = date('Y-m-d H:i:s', time());
                            $provider_account_rate_data['balance'] = $providerAccountNewDecInfo['account_balance'];
                            $provider_account_rate_data['remark'] = 'top_order_tour.id:' . I('id');
                            $provider_account_rate_data['object_id'] = I('id');
                            $provider_account_rate_data['object_type'] = Top::ObjectTypeTour;
                            $provider_account_rate_data['object_name'] = '线路';
                            //向 account_transaction 表插入一条供应商减钱的记录
                            $provider_account_rate_delmoney = M('account_transaction')->add($provider_account_rate_data);
                            //end

                            $sys_list = M('sys')->where("id = 1")->find();
                            $sys_data['account_balance'] = $sys_list['account_balance'];
                            $sys_data['update_time'] = date('Y-m-d H:i:s', time());
                            $sys_data['account_balance'] = $commissionFen + $sys_data['account_balance'];
                            //将一条系统增加佣金金额的信息更新 sys 表
                            $sys = M('sys')->where("id = 1")->save($sys_data);

                            $sys_list = M('sys')->where("id = 1")->find();

                            $sys_account_data['operator_id'] = 0;
                            $sys_account_data['action'] = '收入线路产品订单佣金';
                            $sys_account_data['entity_type'] = Top::EntityTypeSystem;
                            $sys_account_data['entity_id'] = $sys_list['id'];
                            $sys_account_data['account'] = $sys_list['account'];
                            $sys_account_data['balance'] = $sys_list['account_balance'];
                            $sys_account_data['sn'] = Utils::getSn();
                            $sys_account_data['batch'] = $nowTime;
                            $sys_account_data['amount'] = $commissionFen;
                            $sys_account_data['create_time'] = date('Y-m-d H:i:s', time());
                            $sys_account_data['balance'] = $sys_list['account_balance'];
                            $sys_account_data['remark'] = 'top_order_tour.id:' . I('id');
                            $sys_account_data['object_id'] = I('id');
                            $sys_account_data['object_type'] = Top::ObjectTypeTour;
                            $sys_account_data['object_name'] = '线路';
                            //向 account_transaction 表插入一条运营商增加金额的信息
                            $sys_account_list = M('account_transaction')->add($sys_account_data);

                            $operator_account_data['operator_id'] = $operatorList['id'];
                            $operator_account_data['transaction_type'] = 1;
                            $operator_account_data['profit_rate'] = $operatorList['profit_rate'];
                            $operator_account_data['action'] = '收入线路产品订单佣金';
                            $operator_account_data['entity_type'] = Top::EntityTypeOperator;
                            $operator_account_data['entity_id'] = $operatorList['id'];
                            $operator_account_data['account'] = $operatorList['account'];
                            $operator_account_data['amount'] = $commissionFen;
                            $operator_account_data['sn'] = Utils::getSn();
                            $operator_account_data['batch'] = $nowTime;
                            $operator_account_data['create_time'] = date('Y-m-d H:i:s', time());
                            $operator_account_data['balance'] = $operatorList['account_balance'];
                            $operator_account_data['remark'] = 'top_order_tour.id:' . I('id');
                            $operator_account_data['object_id'] = I('id');
                            $operator_account_data['object_type'] = Top::ObjectTypeTour;
                            $operator_account_data['object_name'] = '线路';
                            //向 account_transaction 表插入一条运营商增加金额的信息
                            $operator_account_list = M('account_transaction')->add($operator_account_data);

                        }
                        if ($result && $agency_delmoney && $provider_result && $orderResult && $orderLogResult && $providerAccountResult && $provider_account_addmoney && $operatorCreditBalanceResult && $operator_delmoney) {
                            M('operator')->commit();
                            $data['status'] = 1;
                            $this->ajaxReturn($data);
                        }
                    } catch (Exception $ex) {
                        M('operator')->rollback();
                    }
                } else {
                    $data['status'] = 0;
                    $this->ajaxReturn($data);
                }
            } else {
                $data['status'] = 3;
                $this->ajaxReturn($data);
            }
        }
    }



    public function orderInfo()
    {
        $id = I('id');
        $agencyInfo = $this->userInfo;
        $agencyId = $agencyInfo['id'];
        $orderTourInfo = M('order_tour')->where("id = '{$id}'")->find();
        $couponInfo = M('promotion_coupon')->where("order_id = '{$id}' && agency_id = '{$agencyId}'")->find();

        if ($couponInfo) {
            $couponStatus = '1';
        } else {
            $couponStatus = '0';
        }

        $this->assign('list', $orderTourInfo);
        $this->assign('couponStatus', $couponStatus);
        $this->assign('couponInfo', $couponInfo);
        $this->display();
    }



    public function otherOrderInfo()
    {
        $id = I('id');
        $orderTourInfo = M('order_product')->where("id = '{$id}'")->find();
        $this->assign('list', $orderTourInfo);
        $this->display();
    }


    protected function myorderListGetPageHtml($page)
    {
        $M = M();
        $userList = $this->userInfo;

        $where = $userList['id'];

        $pageSize = 4;
        $index = ($page - 1) * $pageSize;

        $list = $M->table('top_tour as t,top_order_tour as o')
            ->where("o.agency_id='{$where}' && o.tour_id=t.id")
            ->field(array(
                'o.id' => 'id',
                't.name' => 'name',
                'o.client_adult_count' => 'client_adult_count',
                'o.client_child_count' => 'client_child_count',
                'o.start_time' => 'start_time',
                'o.price_total' => 'price_total',
                'o.price_adjust' => 'price_adjust',
                'o.prepay_amount' => 'prepay_amount',
                'o.state' => 'state',
                'o.create_time' => 'create_time',
                't.cover_pic' => 'cover_pic',
                'o.memo' => 'memo',
                'o.fullpay_time' => 'fullpay_time',
                'o.prepay_time' => 'prepay_time',
            ))
            ->order('o.id desc')
            ->limit($index, $pageSize)
            ->select();


        foreach ($list as $key => $value) {
            $list[$key]['price_total'] = Utils::getYuan($value['price_total']);
            $list[$key]['price_adjust'] = Utils::getYuan($value['price_adjust']);

            $list[$key]['price_payable'] = Utils::getYuan($value['price_total'] + $value['price_adjust']);

            $list[$key]['start_time'] = substr($value['start_time'], 0, 10);

            if ($list[$key]['fullpay_time'] != '') {
                $list[$key]['fullpay_time'] = date('Y-m-d H:i:s', strtotime('+30 day', strtotime($value['fullpay_time'])));
            }

            if ($list[$key]['prepay_time'] != '') {
                $list[$key]['prepay_time'] = date('Y-m-d H:i:s', strtotime('+30 day', strtotime($value['prepay_time'])));
            }
        }

        $Pic = array();
        foreach ($list as $key => $vo) {

            $coverPic = $vo['cover_pic'];
            $url = str_replace("#file1#", C('FILE1_BASE_URL'), $coverPic);
            $Pic[] = Utils::GetImageUrl($url, 240, 160, 1);


            if ($vo['cover_pic'] == '') {
                $coverPic = "<img src='" . __ROOT__ . "/Public/images/temp/1.jpg'/>";
            } else {
                $coverPic = "<img src='" . $Pic[$key] . "'/>";
            }

            if ($vo['state'] == 1) {
                $state = '未提交';
            } elseif ($vo['state'] == 2) {
                $state = '已提交';
            } elseif ($vo['state'] == 3) {
                $state = '已确认待付款';
            } elseif ($vo['state'] == 4) {
                $state = '已取消';
            } elseif ($vo['state'] == 5) {
                $state = '已关闭';
            } elseif ($vo['state'] == 6) {
                $state = '已付预付款';
            } elseif ($vo['state'] == 7) {
                $state = '已付全款';
            } elseif ($vo['state'] == 8) {
                $state = '已退款';
            } elseif ($vo['state'] == 9) {
                $state = '取消中';
            } elseif ($vo['state'] == 10) {
                $state = '取消中';
            } elseif ($vo['state'] == 11) {
                $state = '取消被拒绝';
            } elseif ($vo['state'] == 12) {
                $state = '取消中';
            } elseif ($vo['state'] == 13) {
                $state = '已取消';
            }

            $nowDate = date("Y-m-d H:i:s", time());
            //判断状态是否为 已确认待付款
            if ($vo['state'] == 3) {
                if ($vo['prepay_amount'] == '' || $vo['prepay_amount'] == 0) {
                    $show = "&nbsp;&nbsp;<p>
						<a href=" . U('Personal/showAllPayed', array('id' => $vo['id'])) . " class='btn btn-success btn-sm'>
							付全款
						</a></p>";
                } else {
                    $show = "&nbsp;&nbsp;<p>
						<a href=" . U('Personal/showPrePayed', array('id' => $vo['id'])) . " class='btn btn-info btn-sm'>
							付预付款
						</a>&nbsp;&nbsp;<a href=" . U('Personal/showAllPayed', array('id' => $vo['id'])) . " class='btn btn-success btn-sm'>
							付全款
						</a></p>";
                }
            } else if ($vo['state'] == 6) {
                $show = "&nbsp;&nbsp;<p>
                    <a href=" . U('Personal/showFinalPayment', array('id' => $vo['id'])) . " class='btn btn-info btn-sm'>
                        付尾款
                    </a></p>";
            } else {
                $show = '';
            }

            $evaldata .= "<ul class='list'>";
            $evaldata .= "<li>";
            $evaldata .= "<h3 class='h3t'>" . $vo['name'] . "</h3>";
            $evaldata .= "<dl class='clearfix'>";
            $evaldata .= "<dt><a href='" . U('Personal/orderInfo', array('id' => $vo['id'])) . "'>" . $coverPic . "</a></dt>";
            $evaldata .= "<dd>";
            $evaldata .= "<p><span class='mr'>成人<dfn>" . $vo['client_adult_count'] . "</dfn></span><span class='mr'> 儿童<dfn>" . $vo['client_child_count'] . "</dfn></span><span class='mr'>团期" . $vo['start_time'] . "</span></p>";
            $evaldata .= "<p class='mr'>下单时间：<em>" . $vo['create_time'] . "</em></p>";
            $evaldata .= "<p class='price'>订单金额：<em><dfn>&yen;" . $vo['price_total'] . "</dfn></em></p>";
            $evaldata .= "<p class='price'>调整金额：<em><dfn>&yen;" . $vo['price_adjust'] . "</dfn></em></p>";
            $evaldata .= "<p class='price'>应付金额：<em><dfn>&yen;" . $vo['price_payable'] . "</dfn></em></p>";
            $evaldata .= "<p class='prie'>特别说明：<em><dfn>" . $vo['memo'] . "</dfn></em></p>";
            $evaldata .= "<p>订单状态：";
            $evaldata .= "<dfn>" . $state . "</dfn></p>";
            $evaldata .= $show;
            $evaldata .= "</dd>";
            $evaldata .= "</dl>";
            $evaldata .= "</li>";
            $evaldata .= "</ul>";
        }

        return $evaldata;
    }
    protected function userFeedbackListGetPageHtml($page)
    {
       
        $userList = $this->userInfo;
        $pageSize = 4;
        $index = ($page - 1) * $pageSize;
        $where['comment_type'] = 0;
        $where['cover_commnet_id'] = $userList['id'];
        $list = M('feedback')->where($where)->order('id desc')->limit($index, $pageSize)->select();
        foreach ($list as $key => $vo) {
            $evaldata .= "<ul class='list'>";
            $evaldata .= "<li>";
            $evaldata .= "<dl class='clearfix'>";
            $evaldata .= "<dd>";
            $evaldata .= "<p class='mr'>意见反馈时间：<em>" . $vo['create_time'] . "</em></p>";
            $evaldata .= "<p class='mr'>意见反馈人：<em>" . $vo['agency_name'] . "</em></p>";
            $evaldata .= "<p class='price'>评星：<em><dfn>" . $vo['star'] . "</dfn></em></p>";
            $evaldata .= "<p class='price'>反馈内容：<em><dfn>" . $vo['comm_content'] . "</dfn></em></p>";
            $evaldata .= "</dd>";
            $evaldata .= "</dl>";
            $evaldata .= "</li>";
            $evaldata .= "</ul>";
        }

        return $evaldata;
    }



    protected function otherOrderListGetPageHtml($page)
    {
        $M = M();
        $userList = $this->userInfo;

        $where = $userList['id'];

        $pageSize = 4;
        $index = ($page - 1) * $pageSize;

        $list = $M->table('top_order_product as o,top_product as t')
            ->where("o.agency_id = '{$where}' && o.product_id = t.id")
            ->field(array(
                'o.id' => 'id',
                'o.product_name' => 'product_name',
                'o.quantity' => 'quantity',
                't.cover_pic' => 'cover_pic',
                'o.price_total' => 'price_total',
                'o.price_adjust' => 'price_adjust',
                'o.prepay_amount' => 'prepay_amount',
                'o.state' => 'state',
                'o.create_time' => 'create_time',
                'o.memo' => 'memo',
            ))
            ->order('o.id desc')
            ->limit($index, $pageSize)
            ->select();


        foreach ($list as $key => $value) {
            $list[$key]['price_total'] = Utils::getYuan($value['price_total']);
            $list[$key]['price_adjust'] = Utils::getYuan($value['price_adjust']);

            $list[$key]['price_payable'] = Utils::getYuan($value['price_total'] + $value['price_adjust']);
        }

        $Pic = array();

        foreach ($list as $key => $vo) {
            $vo['price'] = Utils::getYuan($vo['price']);
            $coverPic = $vo['cover_pic'];
            $url = str_replace("#file1#", C('FILE1_BASE_URL'), $coverPic);
            $Pic[] = Utils::GetImageUrl($url, 240, 160, 1);

            if ($vo['cover_pic'] == '') {
                $coverPic = "<img src='" . __ROOT__ . "/Public/images/temp/1.jpg'/>";
            } else {
                $coverPic = "<img src='" . $Pic[$key] . "'/>";
            }

            if ($vo['state'] == 1) {
                $state = '未提交';
            } elseif ($vo['state'] == 2) {
                $state = '已提交';
            } elseif ($vo['state'] == 3) {
                $state = '已确认待付款';
            } elseif ($vo['state'] == 4) {
                $state = '已取消';
            } elseif ($vo['state'] == 5) {
                $state = '已关闭';
            } elseif ($vo['state'] == 6) {
                $state = '已付预付款';
            } elseif ($vo['state'] == 7) {
                $state = '已付全款';
            } else {
                $this->error("state is 0");
            }

            //判断状态是否为 已确认待付款
            if ($vo['state'] == 3) {
                if ($vo['prepay_amount'] == '' || $vo['prepay_amount'] == 0) {
                    $show = "&nbsp;&nbsp;<p>
						<a href=" . U('Product/showAllPayed', array('id' => $vo['id'])) . " class='btn btn-success btn-sm'>
							付全款
						</a></p>";
                } else {
                    $show = "&nbsp;&nbsp;<p>
						<a href=" . U('Product/showPrePayed', array('id' => $vo['id'])) . " class='btn btn-info btn-sm'>
							付预付款
						</a>&nbsp;&nbsp;<a href=" . U('Product/showAllPayed', array('id' => $vo['id'])) . " class='btn btn-success btn-sm'>
							付全款
						</a></p>";
                }
            } else if ($vo['state'] == 6) {
                $show = "&nbsp;&nbsp;<p>
						<a href=" . U('Product/showFinalPayment', array('id' => $vo['id'])) . " class='btn btn-info btn-sm'>
							付尾款
						</a></p>";
            } else {
                $show = '';
            }

            $evaldata .= "<ul class='list'>";
            $evaldata .= "<li>";
            $evaldata .= "<h3 class='h3t'>" . $vo['product_name'] . "</h3>";
            $evaldata .= "<dl class='clearfix'>";
            $evaldata .= "<dt><a href='" . U('Personal/otherOrderInfo', array('id' => $vo['id'])) . "'>" . $coverPic . "</a></dt>";
            $evaldata .= "<dd>";
            $evaldata .= "<p><span class='mr'>数量 <dfn>" . $vo['quantity'] . "</dfn></p>";
            $evaldata .= "<p class='mr'>下单时间：<em>" . $vo['create_time'] . "</em></p>";
            $evaldata .= "<p class='price'>订单金额：<em><dfn>&yen;" . $vo['price_total'] . "</dfn></em></p>";
            $evaldata .= "<p class='price'>调整金额：<em><dfn>&yen;" . $vo['price_adjust'] . "</dfn></em></p>";
            $evaldata .= "<p class='price'>应付金额：<em><dfn>&yen;" . $vo['price_payable'] . "</dfn></em></p>";
            $evaldata .= "<p class='prie'>特别说明：<em><dfn>" . $vo['memo'] . "</dfn></em></p>";
            $evaldata .= "<p>订单状态：";
            $evaldata .= "<dfn>" . $state . "</dfn></p>";
            $evaldata .= $show;
            $evaldata .= "</dd>";
            $evaldata .= "</dl>";
            $evaldata .= "</li>";
            $evaldata .= "</ul>";
        }

        return $evaldata;
    }


    protected function myRecommendListGetPageHtml($page)
    {
        $M = M();

        $userList = $this->userInfo;

        $where = $userList['id'];

        //每页显示数量
        $pageSize = 4;
        $index = ($page - 1) * $pageSize;

        $list = $M->table('top_agency_tour as a,top_tour as t')
            ->where("a.tour_id=t.id && a.agency_id='{$where}'")
            ->field(array(
                't.name' => 'name',
                'a.id' => 'id',
                't.min_price' => 'min_price',
                't.cover_pic' => 'cover_pic',
                'a.tour_id' => 'tour_id',
            ))
            ->order('t.id desc')
            ->limit($index, $pageSize)
            ->select();
        $Pic = array();
        foreach ($list as $key => $vo) {
            $coverPic = $vo['cover_pic'];
            $url = str_replace("#file1#", C('FILE1_BASE_URL'), $coverPic);
            $Pic[] = Utils::GetImageUrl($url, 240, 160, 1);
            $vo['min_price'] = Utils::getYuan($vo['min_price']);
            if ($vo['cover_pic'] == '') {
                $coverPic = "<img src='" . __ROOT__ . "/Public/images/temp/1.jpg'/>";
            } else {
                $coverPic = "<img src='" . $Pic[$key] . "'/>";
            }

            $evaldata .= "<dl class='item clearfix'>";
            $evaldata .= "<dt>";
            $evaldata .= "<a href=" . U('Agency/details', array('id' => $vo['tour_id'])) . ">" . $coverPic . "</a>";
            $evaldata .= "</dt>";
            $evaldata .= "<dd>";
            $evaldata .= "<p class='name'><a href=" . U('Agency/details', array('id' => $vo['tour_id'])) . ">" . $vo['name'] . "</a></p>";
            $evaldata .= "<span class='price'><dfn>&yen;" . $vo['min_price'] . "</dfn>起</span>";
            $evaldata .= "<a href=" . U('Personal/delete', array('id' => $vo['id'])) . " class='del'>删除</a>";
            $evaldata .= "</dd>";
            $evaldata .= "</dl>";
        }

        return $evaldata;
    }


    public function myGuest()
    {
        $this->display();
    }



    public function providerQuery()
    {
        $operatorId = $this->userInfo['operator_id'];

        if (IS_POST) {
            $name = I('name');
            $queryList = M('provider')->where("operator_id = '{$operatorId}' and state = 1 and row_state = 0 and (name like '%%$name%%' or full_name like '%%$name%%' or destinations like '%%$name%%' or description like '%%$name%%')")->select();
        } else {
            $date = date('m');
            $start_date = date('Y-m-d 00:00:00', mktime(00, 00, 00, date($date, strtotime($date)) - 0, 01));
            $end_date = date('Y-m-d 23:59:59', mktime(23, 59, 59, date($date, strtotime($date)) + 1, 00));

            $list = M('provider')->where("create_time >= '{$start_date}' and create_time <= '{$end_date}' and operator_id = '{$operatorId}' and state = 1 and row_state = 0")->select();
        }

        $this->assign('name', $name);
        $this->assign('queryList', $queryList);
        $this->assign('list', $list);
        $this->display();
    }



    public function lists()
    {
        $isLogin = session('isLogin');
        if ($isLogin == 'yes') {
            $page = I('page');
            $providerId = I('id');

            if ($page == '') {
                $page = 1;
            }

            $html = $this->myProviderListGetPageHtml($page, $providerId);

            if (IS_POST && IS_AJAX) {
                $this->ajaxReturn($html, $providerId);
            } else {
                $this->assign('html', $html);
            }

            $this->display();
        } else {
            $domain = $_SERVER['SERVER_NAME'];
            $url = "http://" . $domain . "/index.php";
            header("Location:" . $url);
        }
    }



    public function myProviderListGetPageHtml($page, $providerId)
    {
        $M = M();
        $userList = $this->userInfo;
        $operatorId = $this->userInfo['operator_id'];

        $pageSize = C('PRODUCT_PAGE_SET');
        $index = ($page - 1) * $pageSize;

        $list = $M->table('top_tour')
            ->where("provider_id = '{$providerId}' and operator_id = '{$operatorId}'")
            ->field('id,name,min_price,start_time,cover_pic')
            ->limit($index, $pageSize)
            ->order('id desc')
            ->select();

        $agencyId = $userList['id'];

        $agenyTourList = M('agency_tour_price')->where("agency_id = '{$agencyId}'")->field('agency_id,tour_id,min(price_adult_list) price_adult_list')->group('tour_id')->select();

        $arr3 = array();
        foreach ($list as $key => $vo) {
            foreach ($agenyTourList as $k => $v) {
                if ($vo['id'] == $v['tour_id']) {
                    $arr3[$key]['id'] = $vo['id'];
                    $list[$key]['min_price'] = min((int)$vo['min_price'], (int)$v['price_adult_list']);
                } else {
                    $arr3[$key]['id'] = $vo['id'];
                    $arr3[$key]['min_price'] = Utils::getYuan($vo['min_price']);
                }
            }
        }

        $Pic = array();
        foreach ($list as $key => $vo) {
            $coverPic = $vo['cover_pic'];
            $url = str_replace("#file1#", C('FILE1_BASE_URL'), $coverPic);
            $Pic[] = Utils::GetImageUrl($url, 240, 160, 1);

            $vo['min_price'] = Utils::getYuan($vo['min_price']);

            if ($vo['cover_pic'] == '') {
                $coverPic = "<img class='lazy' data-original='" . __ROOT__ . "/Public/images/temp/1.jpg'/>";
            } else {
                $coverPic = "<img class='lazy' data-original='" . $Pic[$key] . "'/>";
            }

            $evaldata .= "<dl class='item clearfix'>";
            $evaldata .= "<dt><a href=" . U('Agency/details', array('id' => $vo['id'])) . ">" . $coverPic . "</a></dt>";
            $evaldata .= "<dd>";
            $evaldata .= "<a href=" . U('Agency/details', array('id' => $vo['id'])) . ">";
            $evaldata .= "<p class='name'>" . $vo['name'] . "</p>";
            $evaldata .= "<div class='mid clearfix'>";
            $evaldata .= "<span class='price pull-right'><dfn>&yen;" . $vo['min_price'] . "</dfn>起</span>";
            $evaldata .= "</div>";
            $evaldata .= "<div class='bottom clearfix'>";
            $evaldata .= "<span class='date pull-left'>" . $vo['start_time'] . "</span>";
            $evaldata .= "<span class='ck pull-right'>[详情]</span>";
            $evaldata .= "</div>";
            $evaldata .= "</a>";
            $evaldata .= "</dd>";
            $evaldata .= "</dl>";
        }

        return $evaldata;
    }

}
